<template>
  <div>
    <div id="container" class="map-container"></div>
    <div class="input-card">
      <h4>轨迹回放控制</h4>
      <div class="input-item">
        <button class="btn" @click="startAnimation">开始动画</button>
        <button class="btn" @click="pauseAnimation">暂停动画</button>
      </div>
      <div class="input-item">
        <button class="btn" @click="resumeAnimation">继续动画</button>
        <button class="btn" @click="stopAnimation">停止动画</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";

let marker: any = null;
let map: any = null;
let passedPolyline: any = null;
const lineArr = [
  [119.546762, 35.402793],
  [119.548172, 35.402793],
  [119.549638, 35.402793],
  [119.550714, 35.402861],
  [119.552571, 35.402907],
  [119.552655, 35.403396],
  [119.553115, 35.40376],
  [119.553953, 35.403931],
  [119.554847, 35.40409],
  [119.555852, 35.404295],
  [119.555838, 35.405001],
  [119.5558, 35.405775],
  [119.555796, 35.407015],
];

// 声明 AMap 类型
declare let AMapLoader: any;
declare let AMap: any;

onMounted(async () => {
  try {
    await AMapLoader.load({
      key: "d7d12ba421394f509cdc82132a03fc94",
      version: "2.0",
      plugins: ["AMap.MoveAnimation"],
    });
    initMap();
  } catch (e) {
    console.error("高德地图加载失败:", e);
  }
});
const initMap = () => {
  AMap.plugin("AMap.MoveAnimation", function () {
    map = new AMap.Map("container", {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 17,
    });

    marker = new AMap.Marker({
      map: map,
      position: [119.546762, 35.402793],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
      offset: new AMap.Pixel(-13, -26),
      angle: 90, // 设置初始旋转角度为90度
    });

    // 绘制轨迹
    let polyline = new AMap.Polyline({
      map: map,
      path: lineArr,
      showDir: true,
      strokeColor: "pink", //线颜色
      strokeOpacity: 1, //线透明度
      strokeWeight: 6, //线宽
      strokeStyle: "solid", //线样式
    });

    passedPolyline = new AMap.Polyline({
      map: map,
      strokeColor: "red", //线颜色
      strokeWeight: 6, //线宽
    });

    marker.on("moving", function (e: any) {
      passedPolyline.setPath(e.passedPath);
      map.setCenter(e.target.getPosition(), true);
    });

    map.setFitView();
  });
};

const startAnimation = () => {
  marker.moveAlong(lineArr, {
    duration: 1000,
    autoRotation: true,
  });
};

const pauseAnimation = () => {
  marker.pauseMove();
};

const resumeAnimation = () => {
  marker.resumeMove();
};

const stopAnimation = () => {
  marker.stopMove();
};
</script>

<style>
.map-container {
  height: 100vh;
  width: 100%;
}

.input-card {
  position: absolute;
  bottom: 50px;
  right: 50px;
  background-color: white;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
  z-index: 1000;
}

.input-card .btn {
  margin-right: 1.2rem;
  width: 9rem;
}

.input-card .btn:last-child {
  margin-right: 0;
}
</style>
